package com.itheima.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author MI
 * @ClassName ExceptionHadlerPage.java
 * @createTime 2021年11月17日 22:27:00
 * 自定义返回异常页面
 */
@Component
public class ExceptionHadlerPage implements UrlBlockHandler {
    /**
     * Handle the request when blocked.
     *
     * @param request  Servlet request
     * @param response Servlet response
     * @param ex       the block exception.
     * @throws IOException some error occurs
     */
    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws IOException {
        ResponseData responseData = null;
        if (ex instanceof FlowException) {
            responseData = new ResponseData(-1, "接口被限流了");
        } else if (ex instanceof DegradeException) {
            responseData = new ResponseData(-2, "接口被限流了");
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(response));
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class ResponseData {
    private int code;
    private String message;
}
